package ntd.util.ftp;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.ftp.SimpleFtpServer;
import org.apache.ftpserver.usermanager.impl.BaseUser;
import org.apache.ftpserver.usermanager.impl.WritePermission;

public class NtdFtpServer {

    private String username;
    private String password;
    private Integer port;
    private String directory;

    public NtdFtpServer(Integer port, String directory, String username, String password) {
        this.username = username;
        this.password = password;
        this.port = port;
        this.directory = directory;
        this.init();
    }

    public NtdFtpServer(Integer port, String directory) {
        this(port, directory, null, null);
    }

    private void init() {
        // 如果文件夹不存在则自动创建
        FileUtil.mkdir(directory);

        SimpleFtpServer simpleFtpServer = SimpleFtpServer.create();
        simpleFtpServer.setPort(port);
        if (StrUtil.isAllNotBlank(username, password)) {
            BaseUser user = new BaseUser();
            user.setName(username);
            user.setPassword(password);
            user.setHomeDirectory(directory);
            user.setAuthorities(ListUtil.of(new WritePermission()));
            simpleFtpServer.addUser(user);
        } else {
            simpleFtpServer.addAnonymous(directory);
        }
        simpleFtpServer.start();
    }

}
